package com.iceberg;

import javax.swing.*;
import java.awt.*;

public class AlgorithmFrame extends JFrame{

    private int canvasWidth;
    private int canvasHeight;

    public AlgorithmFrame(String title, int canvasWidth, int canvasHeight){

        super(title);

        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;

        AlgorithmCanvas canvas = new AlgorithmCanvas();
        setContentPane(canvas);
        pack();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        setVisible(true);
    }

    public AlgorithmFrame(String title){
        this(title, 1024, 768);
    }

    public int getCanvasWidth(){return canvasWidth;}
    public int getCanvasHeight(){return canvasHeight;}

    // TODO: 设置自己的数据
    private MazeData data;
    public void render(MazeData data){
        this.data = data;
        repaint();
    }

    private class AlgorithmCanvas extends JPanel{

        public AlgorithmCanvas(){
            // 双缓存
            super(true);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D)g;

            // 抗锯齿
            RenderingHints hints = new RenderingHints(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.addRenderingHints(hints);

            // 具体绘制
            // TODO： 绘制自己的数据data
            int w = canvasWidth / data.M();
            int h = canvasHeight / data.N();
            AlgorithmVisHelper.setColor(g2d, AlgorithmVisHelper.LightBlue);
            for (int i = 0; i < data.N(); i ++){
                for (int j = 0; j < data.M(); j ++){
                    if (data.getData(i, j) == data.WALL)
                        AlgorithmVisHelper.setColor(g2d, AlgorithmVisHelper.LightBlue);
                    else
                        AlgorithmVisHelper.setColor(g2d, AlgorithmVisHelper.White);
                    if (data.path[i][j])
                        AlgorithmVisHelper.setColor(g2d, AlgorithmVisHelper.Yellow);
                    if (data.result[i][j])
                        AlgorithmVisHelper.setColor(g2d, AlgorithmVisHelper.Red);

                    AlgorithmVisHelper.fillRectangle(g2d, j * w, i * h, w, h);
                }
            }
        }

        @Override
        public Dimension getPreferredSize(){
            return new Dimension(canvasWidth, canvasHeight);
        }
    }
}


